<template>
  <!-- 用户管理页面容器 -->
  <div class="user-management">
      <h2>用户管理</h2>
      <!-- 搜索功能区域 -->
      <div class="actions">
        <el-input
          v-model="search.username"
          placeholder="输入用户名搜索"
          style="width: 200px; margin-right: 10px"
        />
        <el-input
          v-model="search.cardNumber"
          placeholder="输入卡号搜索"
          style="width: 200px; margin-right: 10px"
        />
        <el-input
          v-model="search.cardName"
          placeholder="输入持卡人姓名搜索"
          style="width: 200px; margin-right: 10px"
        />
        <el-select
            v-model="search.status"
            placeholder="选择账户状态"
            style="width: 150px; margin-right: 10px"
            @change="fetchUsers"
        >
          <el-option label="全部" :value="-1" />
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="fetchUsers">搜索</el-button>
      </div>

      <!-- 批量操作功能区域 -->
      <div class="actions">
        <el-button type="danger"  :disabled="selectedUser.length === 0" @click="batchDeleteUsers">删除</el-button>
        <el-button type="warning" :disabled="selectedUser.length === 0" @click="batchUpdateStatus(0)">禁用</el-button>
        <el-button type="success" :disabled="selectedUser.length === 0" @click="batchUpdateStatus(1)">启用</el-button>
        <el-button type="primary" :disabled="selectedUser.length !== 1" @click="getUserDetails(selectedUser[0]?.userId)">查看详情</el-button>
        <el-button type="info"    :disabled="selectedUser.length !== 1" @click="openUpdatePasswordDialog(selectedUser[0])">更新密码</el-button>
        <el-button type="warning" :disabled="selectedUser.length !== 1" @click="openUpdateNameDialog(selectedUser[0])">更新用户名和姓名</el-button>
      </div>

      <!-- 用户表格显示 -->
      <el-table
        :data="userData.content"
        style="width: 100%"
        :height="500"
        row-key="userId"
        v-loading="loading"
        virtual-scroll
        :selection="selectedUser"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" width="70" :index="indexMethod" />
        <el-table-column prop="userId" label="用户ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="cardName" label="姓名" />
        <el-table-column prop="cardNumber" label="卡号" width="110" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-actions">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total, jumper"
          :total="userData.totalElements"
          :page-size="pagination.size"
          v-model:current-page="pagination.page"
          @update:currentPage="fetchUsers"
          @size-change="handleSizeChange"
        />
      </div>
    <!-- 更新密码弹窗 -->
    <el-dialog
      title="更新密码"
      v-model="dialogVisible"
      width="400px"
      @close="clearForm"
    >
      <el-form :model="updateForm" >
        <el-form-item label="新密码" required>
          <el-input type="password" v-model="updateForm.newPassword" placeholder="请输入新密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePassword">保存</el-button>
      </div>
    </el-dialog>

    <!-- 更新用户名和姓名弹窗 -->
    <el-dialog
      title="更新用户名和姓名"
      v-model="updateNameDialogVisible"
      width="400px"
      @close="clearNameForm"
    >
      <el-form :model="updateNameForm">
        <el-form-item label="用户名" required>
          <el-input v-model="updateNameForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="updateNameForm.cardName" placeholder="请输入姓名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateNameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserNameAndCardName">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, shallowRef } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { debounce } from 'lodash-es';
import http from '../utils/axios';
import dayjs from 'dayjs';

/* --- 工具函数 --- */
const indexMethod = (index) => index + 1;
const formatDate = (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss');

const userData = ref({ content: [], totalElements: 0 });
const pagination = ref({page: 1,size: 10,});
const search = ref({username: '',cardNumber: '',cardName: '',status: null});
const selectedUser = shallowRef([]); // 选中的用户
const dialogVisible = shallowRef(false);// 防止深层嵌套被 Vue 自动响应式化
const updateForm = ref({newPassword: '',userId: null,});
const updateNameDialogVisible = shallowRef(false);
const updateNameForm = ref({username: '',cardName: '',userId: null,});
const loading = ref(false);

const openUpdatePasswordDialog = (user) => {
  updateForm.value.userId = user.userId; // 初始化用户ID
  dialogVisible.value = true; // 打开更新密码弹窗
};
const openUpdateNameDialog = (user) => {
  updateNameForm.value.userId = user.userId; // 初始化用户ID
  updateNameForm.value.username = user.username; // 填充用户名
  updateNameForm.value.cardName = user.cardName; // 填充姓名
  updateNameDialogVisible.value = true; // 打开更新用户名和姓名弹窗
};
const clearForm = () => {
  updateForm.value.newPassword = ''; // 清空密码
  updateForm.value.userId = null; // 清空用户ID
};
const clearNameForm = () => {
  updateNameForm.value.username = ''; // 清空用户名
  updateNameForm.value.cardName = ''; // 清空姓名
  updateNameForm.value.userId = null; // 清空用户ID
};
const handleSelectionChange = (val) => {
  selectedUser.value = val;
};
const handleSizeChange = (size) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  fetchUsers();
};

/* --- 事件处理 --- */
const batchUpdateStatus = async (status) => {
  if (selectedUser.value.length === 0) {
    ElMessage.error('请先选择用户');
    return;
  }
  const userIds = selectedUser.value.map(user => user.userId).filter(Boolean);
  if (userIds.length === 0) {
    ElMessage.error('选中的用户数据无效');
    return;
  }
  try {
    const response = await http.put('/user/batch/update/status', {
      userIds,
      status,
    });
    if (response.status) {
      ElMessage.success(response.data || '更新状态成功');
      await fetchUsers();
    } else {
      ElMessage.error(response.data || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新状态失败：' + error.message);
  }
};

const batchDeleteUsers = async () => {
  try {
    if (selectedUser.value.length === 0) {
      ElMessage.error('请先选择用户');
      return;
    }
    const userIds = selectedUser.value.map(user => user.userId);
    await ElMessageBox.confirm('确认删除选中的用户？', '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const response = await http.delete('/user/batch/delete', {
      data: { userIds },
    });
    if (response.status) {
      ElMessage.success(response.data || '删除成功');
      await fetchUsers();
    } else {
      ElMessage.error(response.data || '部分或全部用户删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败：' + error.message);
  }
};

const updatePassword = async () => {
  try {
    const { newPassword, userId } = updateForm.value;
    if (!newPassword) { 
      ElMessage.error('密码不能为空');
      return;
    }
    const response = await http.put('/user/update/password', { userId, newPassword });
    if (response.status) {
      ElMessage.success(response.data || '密码更新成功');
      dialogVisible.value = false;
      await fetchUsers();
    } else {
      ElMessage.error(response.data || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败：' + error.message);
  }
};

const updateUserNameAndCardName = async () => {
  try {
    const { username, cardName, userId } = updateNameForm.value;
    if (!username || !cardName) { 
      ElMessage.error('用户名和姓名不能为空');
      return;
    }
    const response = await http.put('/user/update/name', { userId, username, cardName });
    if (response.status) {
      ElMessage.success(response.data || '姓名和用户名更新成功');
      updateNameDialogVisible.value = false; // 关闭对话框
      await fetchUsers();
    } else {
      ElMessage.error(response.data || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败：' + error.message);
  }
};

const getUserDetails = async (userId) => {
  if (!userId) {
    ElMessage.error('未选择用户');
    return;
  }
  try {
    const response = await http.post('/user/getUserInfo', { userId });
    const data = response.data;
    await ElMessageBox.alert(
        `用户ID: ${data.userId}
        <br>用户名: ${data.username}
        <br>姓名: ${data.cardName}
        <br>卡号: ${data.cardNumber}
        <br>状态: ${data.status === 1 ? '正常' : '禁用'}
        <br>创建时间: ${formatDate(data.createTime)}
        <br>更新时间: ${formatDate(data.updateTime)}`,
        '用户详情',
        {dangerouslyUseHTMLString: true}
    );
  } catch (error) {
    ElMessage.error('获取用户详情失败');
  }
};

const fetchUsers = debounce(async () => {
  loading.value = true;
  try {
    const { username, cardNumber, cardName, status } = search.value;
    const queryStatus = status === -1 ? null : status;
    const response = await http.post('/user/all', {
      page: pagination.value.page - 1,
      size: pagination.value.size,
      username: username || undefined,
      cardNumber: cardNumber || undefined,
      cardName: cardName || undefined,
      status: queryStatus,
    });
    userData.value = response.data || { content: [], totalElements: 0 };
  } catch (error) {
    ElMessage.error('获取用户列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
}, 300);

onMounted(fetchUsers);
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.actions {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-actions {
  display: flex;
  align-items: center;
  margin-top: 10px;
  justify-content: space-between;
}

.pagination-actions el-input,
.pagination-actions el-button {
  margin-right: 10px;
}
</style>